using System.Configuration;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;

namespace AspAlliance.SimpleCms
{
    class CmsPageFactory : PageHandlerFactory
    {
        public override IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            CmsSettings cmsConfig = (CmsSettings)ConfigurationManager.GetSection(Resources.ConfigSection);

            // test for cms configuration information
            if (cmsConfig == null)
            {
                // CMS Configuration has not been set. Admin Page will display information regarding the problem.
                return new AdminPage();
            }

            if (context.Request.AppRelativeCurrentExecutionFilePath == cmsConfig.AdminPage)
            {
                return new AdminPage();
            }

            if (context.Request.AppRelativeCurrentExecutionFilePath == cmsConfig.EditPage)
            {
                return new EditPage();
            }

            CmsPage pageData;
            try
            {
                pageData = new CmsPage(context.Request.AppRelativeCurrentExecutionFilePath);
            }
            catch (SqlException)
            {
                return new AdminPage();
            }

            if (pageData.Url != null)
            {
                return new ContentPage();
            }

            return base.GetHandler(context, requestType, url, pathTranslated);
        }
    }
}
